package zj.it.bhne.gridengineeringsurvey.myutils.okhttpnetframe;

import android.os.Handler;
import android.os.StrictMode;
import android.util.Log;

import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;

import java.io.IOException;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import zj.it.bhne.gridengineeringsurvey.myutils.config.NetConfig;

/**
 * Created by 路很长~ on 2018/9/28.
 */

public class OkhttpFrameProcessor implements FrameHttpProcessor {//实现这个接口
    private OkHttpClient mOkhttClient;
    private Handler mHandler;
    public OkhttpFrameProcessor() {
        //这里的设置可以忽略掉认证书
        mOkhttClient = new OkHttpClient().newBuilder().
                connectTimeout(15, TimeUnit.SECONDS)
                .readTimeout(15, TimeUnit.SECONDS)
                .writeTimeout(15, TimeUnit.SECONDS)
                .sslSocketFactory(SSLSocketClient.getSSLSocketFactory())
                .hostnameVerifier(SSLSocketClient.getHostnameVerifier()).build();

        mHandler = new Handler();
    }

    private RequestBody appendBody(Map<String, Object> paramers) {
        FormBody.Builder body = new FormBody.Builder();
        if (paramers == null || paramers.isEmpty()) {
            return body.build();
        }
        for (Map.Entry<String, Object> entry : paramers.entrySet()) {
            body.add(entry.getKey(), entry.getValue().toString());
        }
        return body.build();
    }



    @Override
    public void get(String url, Map<String, Object> parames, final FrameHttpCallback callback) {
        final Request request = new Request.Builder()
                .get()
                .url(url)
                .build();
        mOkhttClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, final IOException e) {
                mHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        callback.onFailure(e.toString());
                    }
                });
            }

            @Override
            public void onResponse(Call call, final Response response) throws IOException {
                if (response.isSuccessful()) {
                    final String result = response.body().string();
                    mHandler.post(new Runnable() {
                        @Override
                        public void run() {
                            callback.onSuccess(result);
                        }
                    });
                } else {
                    mHandler.post(new Runnable() {
                        @Override
                        public void run() {
                            callback.onFailure("访问失败！");
                        }
                    });
                }
            }
        });


    }

    @Override
    public void post(String methodName, Map<String, Object> parames, final FrameHttpCallback callback) {
        StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
                .detectDiskReads().detectDiskWrites().detectNetwork()
                .penaltyLog().build());
        StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
                .detectLeakedSqlLiteObjects().detectLeakedClosableObjects()
                .penaltyLog().penaltyDeath().build());
        try {
            // 命名空间
            String nameSpace = NetConfig.MAIN+NetConfig.TEST;
            // SOAP Action
            String soapAction = nameSpace + methodName;
            SoapObject request = new SoapObject(nameSpace, methodName);
            for (Map.Entry<String, Object> me : parames.entrySet()) {
                // 根据键值对对象获取键和值

                request.addProperty(me.getKey(),me.getValue().toString());
                Log.e("HttpConfig", "callService: "+me.getKey()+"     "+me.getValue().toString() );
            }
            SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
                    SoapEnvelope.VER11);
            envelope.dotNet = true;
            envelope.bodyOut = request;
            envelope.setOutputSoapObject(request);
            envelope.encodingStyle="UTF-8";
            HttpTransportSE transport = new HttpTransportSE(nameSpace);// wsdl文档
            try {
                // 调用WebService
                transport.call(soapAction, envelope);
                // transport.call(null, envelope);
            } catch (Exception e) {
                e.printStackTrace();
            }
            Object obj =  envelope.getResponse();
            callback.onSuccess(obj.toString());
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            callback.onFailure("访问失败！");
        }

        /*RequestBody requestBody = appendBody(parames);
        final Request request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .header("User-Agent", "a")
                .build();
        mOkhttClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, final IOException e) {
                mHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        callback.onFailure(e.toString());
                    }
                });
            }

            @Override
            public void onResponse(Call call, final Response response) throws IOException {
                if (response.isSuccessful()) {
                    final String result = response.body().string();
                    mHandler.post(new Runnable() {
                        @Override
                        public void run() {
                            //Log.e("success",result.toString());
                            callback.onSuccess(result);
                        }
                    });
                } else {
                    mHandler.post(new Runnable() {
                        @Override
                        public void run() {
                            callback.onFailure("访问失败");
                        }
                    });

                }

            }
        });*/



    }
}
